from classes.TestStep import TestStep
from classes.TestCase import TestCase
from classes.PageElementFactory import PageElementFactory
import requests
import json
import time


 

 
def run_test():
    # API端点
    api_url = "http://127.0.0.1:5000/api/test/execute"

     # 自动生成页面元素
    element_dicts = [
        {"name": "username", "locator": "/html/body/div[1]/div/form/div[2]/div/div/div/input", "element_type": "input"},
        {"name": "password", "locator": "/html/body/div[1]/div/form/div[3]/div/div/div/input", "element_type": "input"},
        {"name": "login_btn", "locator": "/html/body/div[1]/div/form/div[4]/div/button", "element_type": "button"}
    ]
    elements = PageElementFactory.from_dicts(element_dicts)

    # 创建测试用例
    case = TestCase("登录测试", browser="chrome", headless=False)
    case.keep_browser_open = True
    
    for elem in elements:
        case.add_element(elem)
    case.add_step(TestStep("open_url", None, url="http://localhost:80/index", timeout=5))
    case.add_step(TestStep("wait_for_element", case.elements["username"], timeout=5))
    # case.add_step(TestStep("input_text", case.elements["username"], text="admin1", timeout=5))
    # case.add_step(TestStep("input_text", case.elements["password"], text="123456", timeout=5))
    case.add_step(TestStep("click", case.elements["login_btn"], timeout=5, retries=3))

    # 生成测试用json数据
    print(case.to_json())

        # 发送请求
    response = requests.post(api_url, json=case.to_dict())
    print("原始响应内容:", response.text)
    result = response.json()
    print("测试执行结果:", json.dumps(result, indent=2))
    
    # 获取测试状态
    if "test_id" in result:
        test_id = result["test_id"]
        status_url = f"http://127.0.0.1:5000/api/test/status/{test_id}"
        
        # 等待测试完成
        time.sleep(5)
        status_response = requests.get(status_url)
        status_result = status_response.json()
        print("测试状态:", json.dumps(status_result, indent=2))




if __name__ == "__main__":
    run_test()
 